﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RanchBuddy.Core.DataAccess;
using RanchBuddy.Core.Services.Impl;
using StructureMap;

namespace RanchBuddy.Core.Domain.Impl
{
    [Pluggable("Default")]
    public partial class Account : IAccount
    {
        public bool IsValid
        {
            get { return GetRuleViolations().Count() == 0;}
        }

        public IEnumerable<RuleViolation> GetRuleViolations()
        {
            if(this.TermID == 0)
                yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(1), "agreeWithTerms");

            if(ValidationService.ValidateDate(this.Birthdate.ToString()))
                yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(2), "birthDate");

            if (!(Username.Length >= ConfigurationService.GetMinimumUsernameLength()) ||
                !(Username.Length <= ConfigurationService.GetMaximumUsernameLength()))
                yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(5), "username");

            if(ValidationService.ValidateUsernameComplexity(Username))
                yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(6), "username");

            if (AccountID == 0 && ObjectFactory.GetInstance<IAccountRepository>().UsernameExists(this.Username))
                yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(7), "username");

            if (!ValidationService.ValidateEmail(Email))
                yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(8), "email");

            if (AccountID == 0 && ObjectFactory.GetInstance<IAccountRepository>().EmailExists(this.Email))
                yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(9), "email");

            yield break;
        }

        public void Validate()
        {
            if(!IsValid)
                throw new ValidationException("Rule violations prevent saving");
        }
    }
}
